import {NodeModulesScanResult} from "../types";
import {FileUtil} from "../utils/FileUtil";
import * as fs from 'fs';
import * as path from 'path';

/**
 * nodeModules扫描器
 */
export class NodeModulesScanner {

  /**
   * 扫描node_modules
   * @param rootPath 扫描根路径
   */
  public static async scan(rootPath: string): Promise<NodeModulesScanResult[] | undefined> {
    try {
      // 修改查找模式，确保只匹配直接的node_modules文件夹，不匹配node_modules内部的node_modules
      const matches = await FileUtil.findPaths(rootPath, {
        depth: 5,
        patterns: ['**/node_modules'],
        // 关键修改：排除node_modules内的node_modules
        excludes: ['**/node_modules/**/node_modules/**']
      });

      if (!matches || matches.length === 0) {
        return undefined;
      }

      // 转换为NodeModulesScanResult数组
      const paths = matches.map(item => {
        return {
          path: item,
        };
      });

      return paths;
    } catch (error) {
      console.error('扫描node_modules失败:', error);
      return undefined;
    }
  }
}
